package com.demo.security.authenticate.sign;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import com.demo.security.HexUtil;
import com.demo.security.RSAUtil;
import com.demo.security.authenticate.Constant;
import com.demo.security.sign.JDKSign;

/**
 * 签名认证服务端
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/17 14:43
 */
public class Server {

    /**
     * 数字签名认证校验
     *
     * @param params
     * @return
     * @throws Exception
     */
    public static boolean validate(Map<String, String> params, String sign) throws Exception {
        Set<String> keySet = params.keySet();
        TreeSet<String> sortSet = new TreeSet<>();
        sortSet.addAll(keySet);
        StringBuilder keyValueStr = new StringBuilder();
        Iterator<String> iterator = sortSet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = params.get(key);
            keyValueStr.append(key).append(value);
        }
        PublicKey publicKey = RSAUtil.string2PublicKey(Constant.CONSUMER_PUBLIC_KEY);
        return JDKSign.verifyMD5withRSA(keyValueStr.toString().getBytes(), HexUtil.hex2bytes(sign), publicKey);
    }

    /**
     * 数字签名响应认证生成
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String getSign(String content) throws Exception {
        PrivateKey privateKey = RSAUtil.string2PrivateKey(Constant.PROVIDER_PRIVATE_KEY);
        byte[] sign = JDKSign.signMD5withRSA(content.getBytes(), privateKey);
        return HexUtil.bytes2Hex(sign);
    }
}
